package com.library.common.wspoint.point;

import com.alibaba.fastjson2.JSON;
import com.library.common.wspoint.WsDataInterface;
import com.library.common.wspoint.conf.GlobalServerPointConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Package: com.library.framework.web.wspoint
 * @ClassName: GlobalServerPoint
 * @Author: Yin
 * @Date: 14:35
 * @Description: 此文件描述信息
 */
@Slf4j
@Component
@ServerEndpoint(value = "/ws/global" , configurator = GlobalServerPointConfig.class)
public class GlobalServerPoint {

    /** 当前所有连接 */
    private static final Map<String, Session> conns = new ConcurrentHashMap<>();

    private String uuid;

    @OnOpen
    public void onOpen(Session session, EndpointConfig sec) {
        String uuid = (String)sec.getUserProperties().get("sessionKey");
        this.uuid = uuid;
        conns.put(uuid,session);
        log.info("[Websocket]已连接");
    }

    @OnClose
    public void onClose(Session session) {
        conns.remove(uuid);
        log.info("[Websocket]客户端已断开");
    }

    @OnError
    public void onError(Session session,Throwable throwable) {
        conns.remove(uuid);
        log.error("[Websocket]客户端连接异常：{}",throwable.toString());
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("[Websocket]客户端传来消息：[{}]",message);
        if(message.contains("GuardAlarm")) {
            if(conns.size() > 0 ) {
                conns.values().forEach(ses -> {
                    try {
                        // 异步发送
                        ses.getAsyncRemote().sendText(message);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        }else {
            session.getAsyncRemote().sendText("HEARTBEAT");
        }
    }

    /** 发送消息 */
    public void send(WsDataInterface data) {
        if(conns.size() > 0 ) {
            conns.values().forEach(session -> {
                try {
                    // 异步发送
                    session.getAsyncRemote()
                        .sendText(JSON.toJSONString(data));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    /** 指定会话断连 */
    public void close(String key) {
        if(conns.containsKey(key)) {
            try {
                conns.get(key).close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

}
